package com.welson.restfultoolx.ui;

import com.intellij.openapi.project.Project;
import com.intellij.ui.components.JBList;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.JBTextField;
import com.intellij.util.ui.JBUI;
import com.welson.restfultoolx.model.ApiInfo;
import com.welson.restfultoolx.model.SearchOptions;
import com.welson.restfultoolx.service.ControllerScannerService;
import com.welson.restfultoolx.service.SearchEngineService;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

/**
 * API列表面板
 * 显示和管理项目中的所有API
 */
public class ApiListPanel extends JPanel {
    
    private final Project project;
    private final ControllerScannerService scannerService;
    private final SearchEngineService searchService;
    
    private JBTextField filterField;
    private JBList<ApiInfo> apiList;
    private DefaultListModel<ApiInfo> listModel;
    private JLabel statusLabel;
    private JPanel detailPanel;
    
    private List<ApiInfo> allApis;
    private Timer filterTimer;
    
    public ApiListPanel(@NotNull Project project) {
        this.project = project;
        this.scannerService = project.getService(ControllerScannerService.class);
        this.searchService = project.getService(SearchEngineService.class);
        
        setLayout(new BorderLayout());
        initComponents();
        loadApis();
    }
    
    private void initComponents() {
        // 创建顶部工具栏
        JPanel toolbarPanel = createToolbarPanel();
        add(toolbarPanel, BorderLayout.NORTH);
        
        // 创建主内容面板
        JPanel contentPanel = createContentPanel();
        add(contentPanel, BorderLayout.CENTER);
        
        // 创建底部状态栏
        JPanel statusPanel = createStatusPanel();
        add(statusPanel, BorderLayout.SOUTH);
    }
    
    private JPanel createToolbarPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(JBUI.Borders.empty(10));
        
        // 过滤输入框
        JLabel filterLabel = new JLabel("Filter:");
        filterLabel.setBorder(JBUI.Borders.emptyRight(5));
        
        filterField = new JBTextField();
        filterField.setToolTipText("Filter APIs by path, method name, or class name");
        filterField.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                scheduleFilter();
            }
            
            @Override
            public void removeUpdate(DocumentEvent e) {
                scheduleFilter();
            }
            
            @Override
            public void changedUpdate(DocumentEvent e) {
                scheduleFilter();
            }
        });
        
        // 刷新按钮
        JButton refreshButton = new JButton("Refresh");
        refreshButton.addActionListener(e -> refreshApis());
        
        JPanel leftPanel = new JPanel(new BorderLayout());
        leftPanel.add(filterLabel, BorderLayout.WEST);
        leftPanel.add(filterField, BorderLayout.CENTER);
        
        JPanel rightPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        rightPanel.add(refreshButton);
        
        panel.add(leftPanel, BorderLayout.CENTER);
        panel.add(rightPanel, BorderLayout.EAST);
        
        return panel;
    }
    
    private JPanel createContentPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        
        // 创建API列表
        listModel = new DefaultListModel<>();
        apiList = new JBList<>(listModel);
        apiList.setCellRenderer(new ApiInfoListCellRenderer());
        apiList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        // 添加选择监听器
        apiList.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    updateDetailPanel();
                }
            }
        });
        
        // 添加双击监听器
        apiList.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    navigateToSelectedApi();
                }
            }
        });
        
        JBScrollPane listScrollPane = new JBScrollPane(apiList);
        listScrollPane.setPreferredSize(new Dimension(400, 300));
        
        // 创建详情面板
        detailPanel = new JPanel(new BorderLayout());
        detailPanel.setBorder(JBUI.Borders.empty(10));
        detailPanel.setPreferredSize(new Dimension(300, 300));
        
        JLabel detailTitle = new JLabel("API Details");
        detailTitle.setFont(detailTitle.getFont().deriveFont(Font.BOLD));
        detailPanel.add(detailTitle, BorderLayout.NORTH);
        
        // 使用分割面板
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, 
            listScrollPane, detailPanel);
        splitPane.setDividerLocation(400);
        splitPane.setResizeWeight(0.6);
        
        panel.add(splitPane, BorderLayout.CENTER);
        
        return panel;
    }
    
    private JPanel createStatusPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(JBUI.Borders.empty(5, 10, 10, 10));
        
        statusLabel = new JLabel("Loading APIs...");
        statusLabel.setFont(statusLabel.getFont().deriveFont(Font.ITALIC));
        
        JLabel helpLabel = new JLabel("Double-click to navigate to source code");
        helpLabel.setFont(helpLabel.getFont().deriveFont(10f));
        helpLabel.setForeground(Color.GRAY);
        
        panel.add(statusLabel, BorderLayout.WEST);
        panel.add(helpLabel, BorderLayout.EAST);
        
        return panel;
    }
    
    private void scheduleFilter() {
        if (filterTimer != null) {
            filterTimer.stop();
        }
        
        filterTimer = new Timer(300, e -> performFilter());
        filterTimer.setRepeats(false);
        filterTimer.start();
    }
    
    private void performFilter() {
        String filterText = filterField.getText().trim();
        
        if (filterText.isEmpty()) {
            updateApiList(allApis);
            return;
        }
        
        if (allApis == null || allApis.isEmpty()) {
            updateApiList(List.of());
            return;
        }
        
        // 执行过滤
        SearchOptions options = SearchOptions.createDefault();
        options.setMaxResults(1000); // 显示更多结果
        List<ApiInfo> filteredApis = searchService.search(filterText, options);
        updateApiList(filteredApis);
    }
    
    private void updateApiList(List<ApiInfo> apis) {
        SwingUtilities.invokeLater(() -> {
            listModel.clear();
            if (apis != null) {
                for (ApiInfo api : apis) {
                    listModel.addElement(api);
                }
            }
            
            // 更新状态
            int count = apis != null ? apis.size() : 0;
            int total = allApis != null ? allApis.size() : 0;
            
            if (filterField.getText().trim().isEmpty()) {
                statusLabel.setText(String.format("Total: %d API(s)", total));
            } else {
                statusLabel.setText(String.format("Showing: %d of %d API(s)", count, total));
            }
            
            // 清空详情面板
            updateDetailPanel();
        });
    }
    
    private void updateDetailPanel() {
        // 移除旧内容
        Component[] components = detailPanel.getComponents();
        for (Component component : components) {
            if (!(component instanceof JLabel)) { // 保留标题
                detailPanel.remove(component);
            }
        }
        
        ApiInfo selectedApi = apiList.getSelectedValue();
        if (selectedApi == null) {
            JLabel emptyLabel = new JLabel("Select an API to view details");
            emptyLabel.setHorizontalAlignment(SwingConstants.CENTER);
            emptyLabel.setForeground(Color.GRAY);
            detailPanel.add(emptyLabel, BorderLayout.CENTER);
        } else {
            // 创建详情面板
            ApiDetailsPanel details = new ApiDetailsPanel(selectedApi);
            detailPanel.add(details, BorderLayout.CENTER);
        }
        
        detailPanel.revalidate();
        detailPanel.repaint();
    }
    
    private void navigateToSelectedApi() {
        ApiInfo selectedApi = apiList.getSelectedValue();
        if (selectedApi != null && selectedApi.getPsiMethod() != null) {
            // 导航到源代码
            if (selectedApi.getPsiMethod().isValid()) {
                selectedApi.getPsiMethod().navigate(true);
            }
        }
    }
    
    private void loadApis() {
        SwingUtilities.invokeLater(() -> {
            statusLabel.setText("Scanning project...");
        });
        
        // 在后台线程中扫描API
        scannerService.scanProjectAsync(project, () -> {
            allApis = scannerService.scanProject(project);
            
            // 构建搜索索引
            searchService.buildIndex(allApis);
            
            SwingUtilities.invokeLater(() -> {
                updateApiList(allApis);
            });
        });
    }
    
    private void refreshApis() {
        // 清空缓存
        scannerService.refreshCache(project);
        searchService.clearIndex();
        
        // 重新加载
        loadApis();
    }
}